<template>
  <el-container class="projectDetail">
    <el-header id="myProgress" class="headerContent">
      <el-button
        v-if="openProjectBtn"
        v-permission="['projectManagement:projectSetting:open']"
        type="text"
        icon="el-icon-menu"
        @click="handleClick('open')"
      >
        打开项目
      </el-button>
      <el-button
        v-permission="['projectManagement:projectSetting:add']"
        type="text"
        icon="el-icon-document-add"
        @click="handleClick('add')"
      >
        新建项目
      </el-button>
      <!-- <el-popconfirm title="确定删除当前项目吗？" @confirm="handleClick('del')">
        <el-button slot="reference" type="text" icon="el-icon-delete">删除当前项目</el-button>
      </el-popconfirm> -->
      <el-button
        v-permission="['projectManagement:projectSetting:close']"
        type="text"
        :disabled="!projectData.projectId"
        icon="el-icon-circle-close"
        @click="handleClick('del')"
      >
        关闭当前项目
      </el-button>
      <el-button
        v-permission="['projectManagement:projectSetting:save']"
        type="text"
        :disabled="!projectData.projectId"
        @click="handleClick('save')"
      >
        <svg-icon icon-class="save" style="font-size: 10px; margin-right: 5px"></svg-icon>
        保存当前配置
      </el-button>
      <el-button
        v-permission="['projectManagement:projectSetting:export']"
        :disabled="!projectData.projectId"
        type="text"
        icon="el-icon-download"
        @click="handleClick('export')"
      >
        导出驱动文件
      </el-button>
    </el-header>
    <el-container style="height: calc(100% - 36px)">
      <el-aside width="280px" class="leftContent">
        <div class="searchBox">
          <el-input v-model="fileterText" placeholder="请输入搜索信息" suffix-icon="el-icon-search"></el-input>
          <div class="manufacturer">
            选择厂家：
            <el-select v-model="manufacturer">
              <el-option
                v-for="manufacturerItem in manufacturerList"
                :key="manufacturerItem"
                :label="manufacturerItem"
                :value="manufacturerItem"
              ></el-option>
            </el-select>
          </div>
        </div>
        <el-scrollbar class="chipContent">
          <div v-for="(chip, chipIndex) in filterChipData" :key="chipIndex" class="chipBox">
            <div class="text">{{ chip.title }}</div>
            <el-collapse v-model="chip.activeName">
              <el-collapse-item
                v-for="(item, index) in chip.data"
                :key="index"
                :title="item.category"
                :name="item.category"
              >
                <div
                  v-for="row in item.chipArray"
                  :key="row.chipId"
                  class="chipInfo"
                  :allData="JSON.stringify(row)"
                >
                  <div class="leftBox">
                    <el-image :src="require('@/assets/imgs/chip.png')" />
                  </div>
                  <div class="rightBox">
                    <div class="tip">
                      名称：
                      <el-tooltip
                        :disabled="getStrLength(row.displayName) < 11"
                        class="item"
                        effect="dark"
                        :content="row.displayName"
                        placement="top"
                      >
                        <span class="ellipsis displayName">
                          {{ row.displayName }}
                        </span>
                      </el-tooltip>
                      <i class="el-icon-document pointer" @click="handleClick('chip', row)" />
                    </div>
                    <el-tooltip
                      :disabled="getStrLength(row.model) < 13"
                      effect="dark"
                      :content="row.model"
                      placement="top"
                    >
                      <div class="tip">
                        型号：
                        <span class="title ellipsis">{{ row.model }}</span>
                      </div>
                    </el-tooltip>
                    <el-tooltip
                      :disabled="getStrLength(row.manufacturer) < 13"
                      effect="dark"
                      :content="row.manufacturer"
                      placement="top"
                    >
                      <div class="tip">
                        厂家：
                        <span class="title ellipsis">{{ row.manufacturer }}</span>
                      </div>
                    </el-tooltip>
                    <el-tooltip
                      :disabled="getStrLength(row.compatible) < 3"
                      effect="dark"
                      :content="row.compatible"
                      placement="top"
                    >
                      <div class="tip">
                        <template v-if="row.type === 1">
                          适配标识：
                          <span class="com_title ellipsis">{{ row.compatible }}</span>
                        </template>
                        <template v-else-if="row.type === 2">
                          适配范围：
                          <!--限制长度6字符串的span-->
                          <span class="com_title ellipsis">{{ row.compatible }}</span>
                        </template>
                      </div>
                    </el-tooltip>
                    <!-- <div class="tip ellipsis">型号：{{ row.model }}</div> -->
                    <!-- <div class="tip ellipsis">厂家：{{ row.manufacturer }}</div> -->
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-scrollbar>
        <chipInfo ref="chipInfo" />
      </el-aside>
      <el-main class="rightContent">
        <MainPage v-if="projectData.name || loading" :title="projectData.name" class="projectContent">
          <chipFlowChart ref="chipFlowChart" :project_data="projectData" @changeCurrentTag="changeCurrentTag" />
        </MainPage>
        <div v-else class="emptyContent">
          <el-empty class="emptyBox" :image="require('@/assets/imgs/empty.png')" description="项目为空">
            <el-button
              v-permission="['projectManagement:projectSetting:add']"
              type="primary"
              @click="handleClick('add')"
            >
              创建项目
            </el-button>
          </el-empty>
          <!-- <div class="emptyBox"><el-button type="primary" @click="handleClick('add')">新建项目</el-button></div> -->
        </div>
      </el-main>
    </el-container>
    <projectTable ref="projectTable" @submit="handleOpen" />
  </el-container>
</template>
<script>
import { getStrLength } from '@/utils/index'
import chipInfo from './chipInfo.vue'
import chipFlowChart from './chip-flow-chart.vue'
import projectTable from './projectTable.vue'
import {
  getChipList,
  getChipDetail,
  saveConfig,
  loadChipCategoryList,
  exportProject
} from '@/api/project-management'
import { fileDownload } from '@/utils/download.js'
import NProgress from 'nprogress'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'

export default {
  components: { chipInfo, chipFlowChart, projectTable },

  props: {
    loading: {
      type: Boolean,
      default: false
    },
    openProjectBtn: {
      type: Boolean,
      default: false
    },
    projectData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      fileterText: '',
      manufacturer: '所有厂家',
      masterChipActiveName: '',
      slaveChipActiveName: '',
      chipData: {},
      category: { masterChipCategory: [], slaveChipCategory: [] },
      getChipListRequestId: generateUUID(),
      loadChipCategoryListRequestId: generateUUID(),
      saveConfigRequestId: generateUUID(),
      exportProjectRequestId: generateUUID(),
      currentRow: {},
      getChipDetailRequestId: generateUUID()
    }
  },
  computed: {
    filterChipData() {
      if (this.fileterText || this.manufacturer) {
        return [
          {
            title: '主控芯片',
            activeName: this.masterChipActiveName,
            data: this.filterData(this.chipData.masterChipArray)
          },
          {
            title: '被控芯片',
            activeName: this.slaveChipActiveName,
            data: this.filterData(this.chipData.slaveChipArray)
          }
        ]
      } else {
        return [
          {
            title: '主控芯片',
            activeName: this.masterChipActiveName,
            data: this.chipData.masterChipArray
          },
          {
            title: '被控芯片',
            activeName: this.slaveChipActiveName,
            data: this.chipData.slaveChipArray
          }
        ]
      }
    },
    manufacturerList() {
      let manufacturerList = ['所有厂家']
      this.chipData?.masterChipArray?.concat(this.chipData?.slaveChipArray).forEach((item) => {
        item.chipArray.forEach((row) => {
          if (!manufacturerList.includes(row.manufacturer)) {
            manufacturerList.push(row.manufacturer)
          }
        })
      })
      return manufacturerList
    }
  },
  mounted() {
    // this.initData()
    receivedMessage(this.dataHandle)
  },
  methods: {
    dataHandle(result) {
      let self = this
      let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
      if (e.data.webInfo.requestId === self.getChipListRequestId) {
        self.setChipList(e.data.response)
      } else if (e.data.webInfo.requestId === self.loadChipCategoryListRequestId) {
        self.category = e.data.response.data
      } else if (e.data.webInfo.requestId === self.saveConfigRequestId) {
        self.afterSaveConfig(e.data.response)
      } else if (e.data.webInfo.requestId === self.exportProjectRequestId) {
        let res = e.data.response
        if (defaultSettings.isOnlineWpf) {
          new Promise((resolve) => {
            if (res.success) {
              var bytes = new Uint8Array(
                window
                  .atob(res.data)
                  .split('')
                  .map(function (c) {
                    return c.charCodeAt(0)
                  })
              )
              res.data = bytes
              fileDownload(res)
            } else {
              self.$message.error(res.message)
            }
            resolve()
          }).then(() => {
            NProgress.done()
          })
        } else {
          if (!res.success) {
            self.$message.error(res.message)
          }
        }
      } else if (e.data.webInfo.requestId === self.getChipDetailRequestId) {
        self.openChipDetail(e.data.response)
      }
    },
    initData() {
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        let message1 = {
          RequestUrl: process.env.VUE_APP_URL + '/chip/getChipList',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: {},
          WebInfo: {
            requestId: this.getChipListRequestId
          }
        }
        postMessage(message1)

        let message2 = {
          RequestUrl: process.env.VUE_APP_URL + '/chip/loadChipCategoryList',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: {},
          WebInfo: {
            requestId: this.loadChipCategoryListRequestId
          }
        }
        postMessage(message2)
      } else {
        getChipList().then((res) => {
          this.setChipList(res)
        })
        this.loadCategoryList()
      }
    },
    getStrLength(str) {
      return getStrLength(str)
    },
    filterData(treeData) {
      let data = []
      treeData?.forEach((item) => {
        let tem = {
          ...item,
          chipArray: []
        }
        item.chipArray.forEach((row) => {
          if (
            (row.displayName.toLowerCase().indexOf(this.fileterText.toLowerCase()) !== -1 ||
              row.model.toLowerCase().indexOf(this.fileterText.toLowerCase()) !== -1) &&
            (this.manufacturer === '所有厂家' || row.manufacturer === this.manufacturer)
          ) {
            tem.chipArray.push(row)
          }
        })
        data.push(tem)
      })
      this.$nextTick(() => {
        const nodeList = document.getElementsByClassName('chipInfo')
        Array.from(nodeList).forEach((node) => {
          node.addEventListener('dragstart', (event) => {
            const allData = JSON.parse(node.getAttribute('allData'))
            /* 设置拖拽传输数据 */
            event.dataTransfer.setData(
              'dragComponent',
              JSON.stringify({
                ...allData,
                chipType: allData.type
              })
            )
          })
        })
      })
      return data
    },
    setChipList(res) {
      this.chipData = res.data
      this.masterChipActiveName = this.chipData?.masterChipArray?.[0]?.category
      this.slaveChipActiveName = this.chipData?.slaveChipArray?.[0]?.category
    },
    loadCategoryList() {
      loadChipCategoryList().then((res) => {
        this.category = res.data
      })
    },
    handleOpen(currentProjectId) {
      this.$emit('handleOpen', 'add', { projectId: currentProjectId })
    },
    openChipDetail(res) {
      if (res.success) {
        let row = {
          ...this.currentRow,
          pinFiles: res.data.pinFiles,
          pinFilesBase64: res.data.pinFilesBase64
        }
        if (row.type === 1) {
          row.clockParameters = res.data.clockParameters
          row.clockParameterFiles = res.data.clockParameterFiles
          row.clockParameterFilesBase64 = res.data.clockParameterFilesBase64
        } else {
          row.performanceParameterFiles = res.data.performanceParameterFiles
          row.performanceParameterFilesBase64 = res.data.performanceParameterFilesBase64
        }
        this.$refs.chipInfo.is(
          row,
          this.currentRow.type === 1 ? this.category.masterChipCategory : this.category.slaveChipCategory
        )
      } else {
        this.$message.error(res.message)
      }
    },
    handleClick(name, row) {
      if (name === 'chip') {
        this.currentRow = row
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          this.getChipDetailRequestId = generateUUID()
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/chip/getChipInfo',
            RequestMethod: 'POST',
            Headers: {
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: { chipId: row.chipId },
            WebInfo: {
              requestId: this.getChipDetailRequestId
            }
          }
          postMessage(message)
        } else {
          getChipDetail({ chipId: row.chipId }).then((res) => {
            this.openChipDetail(res)
          })
        }
      } else if (name === 'open') {
        this.$nextTick(() => {
          this.$refs.projectTable.is()
        })
      } else if (name === 'add') {
        this.$parent.$refs.projectDetail.is('add', {})
      } else if (name === 'del') {
        this.$parent.$refs.tagsView.closeCurrentTag()
      } else if (name === 'save') {
        const data = this.$refs.chipFlowChart.getChartData()
        data.content.nodes.forEach((item) => {
          if (item.data.clockParameterFiles && item.data.clockParameterFiles.length > 0) {
            item.data.clockParameterFilesBase64 = ''
          }
          if (item.data.performanceParameterFiles && item.data.performanceParameterFiles.length > 0) {
            item.data.performanceParameterFilesBase64 = ''
          }
          if (item.data.pinFiles && item.data.pinFiles.length > 0) {
            item.data.pinFilesBase64 = ''
          }
        })
        let params = { projectId: this.projectData.projectId, layoutContent: data }
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          this.saveConfigRequestId = generateUUID()
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/project/saveConfig',
            RequestMethod: 'POST',
            Headers: {
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: params,
            WebInfo: {
              requestId: this.saveConfigRequestId
            }
          }
          postMessage(message)
        } else {
          saveConfig(params).then((res) => {
            this.afterSaveConfig(res)
          })
        }
      } else if (name === 'export') {
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          this.exportProjectRequestId = generateUUID()
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/project/exportDriverFile',
            RequestMethod: 'POST',
            Headers: {
              contentType: 'application/octet-stream'
            },
            QueryParameter: {},
            RequestBody: { projectId: this.projectData.projectId },
            WebInfo: {
              requestId: this.exportProjectRequestId
            }
          }
          postMessage(message)
        } else {
          NProgress.configure({
            parent: '#myProgress'
          }).start()
          exportProject({ projectId: this.projectData.projectId })
            .then((res) => {
              fileDownload(res)
            })
            .finally(() => {
              NProgress.done()
            })
        }
      }
    },
    afterSaveConfig(res) {
      if (res.success) {
        this.$refs.chipFlowChart.setOriginalData()
        this.$emit('initCurrentProject', this.projectData.projectId)
        this.$emit('changeCurrentTag', true)
        this.$message.success('保存当前文件成功')
      } else {
        this.$message.error(res.message)
      }
    },
    changeCurrentTag(isSaved) {
      this.$emit('changeCurrentTag', isSaved)
    }
  }
}
</script>
<style lang="less" scoped>
.projectDetail {
  height: 100%;
  .headerContent {
    height: 36px !important;
    background: #ffffff;
    border: 1px solid #e6e6e6;
    padding-left: 16px;
    .el-button {
      padding-left: 0;
    }
  }
  .progress-container {
    height: 2px;
    position: relative;
    margin-bottom: 10px;
    background-color: #f5f5f5;
    overflow: hidden;
  }

  .leftContent {
    background: #f9f9f9;
    border-right: 2px solid #e6e6e6;
    height: 100%;
    color: #333;
    .searchBox {
      padding: 16px;
      .manufacturer {
        display: flex;
        align-items: center;
        margin-top: 20px;
        font-size: 14px;
        white-space: nowrap;
      }
    }
    .chipContent {
      height: calc(100% - 116px);
      .chipBox:first-of-type .text {
        padding: 0 16px 16px;
      }
      .text {
        padding: 16px;
        font-weight: 600;
      }
      .chipInfo {
        display: flex;
        padding: 16px 16px 0;
        cursor: move;
        user-select: none;
        -webkit-user-drag: element;
        .leftBox {
          // display: flex;
          // justify-content: center;
          // align-items: center;
          width: 84px;
          height: 84px;
          margin-right: 16px;
          flex-shrink: 0;
        }
        .rightBox {
          font-size: 14px;
          font-weight: 400;
          color: #303453;
          flex: 1;
          .tip {
            width: 146px;
            display: flex;
            align-items: center;
            .title {
              display: inline-block;
              max-width: calc(100% - 46px);
              padding: 0;
            }
            .com_title {
              white-space: nowrap; /* 防止换行 */
              overflow: hidden; /* 超出部分隐藏 */
              text-overflow: ellipsis; /* 超出部分用...代替 */
              display: inline-block;
              max-width: calc(100% - 76px);
              padding: 0;
            }
            .displayName {
              display: inline-block;
              max-width: calc(100% - 65px);
              padding: 0;
              margin-right: 5px;
            }
          }
          .tip:not(:last-of-type) {
            margin-bottom: 5px;
          }
        }
      }
      .chipInfo:last-of-type {
        padding-bottom: 16px;
      }
    }
    /deep/.el-collapse {
      border-bottom: none;
    }
    /deep/.el-collapse-item {
      margin-bottom: 1px;
      .el-collapse-item__wrap {
        border-bottom: none;
      }
    }
    /deep/.el-collapse-item__header {
      padding: 0 16px;
      font-weight: bold;
      color: #303453;
      background: #ededed;
    }
    /deep/.el-collapse-item__content {
      font-size: 14px;
      color: #303453;
      padding-bottom: 0;
    }
  }
  .rightContent {
    display: flex;
    flex-direction: column;
    padding: 0;
    font-size: 14px;

    .projectContent {
      flex: 1;
      min-width: 500px;
      overflow: hidden;
    }
    .emptyContent {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      .emptyBox {
        width: 600px;
        height: 350px;
        background-color: #f7f8fa;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
</style>
